const HtmlWebpackPlugin = require('html-webpack-plugin');

class HtmlWebpackPxToRemPlugin {
  constructor(options) {
    this.options = Object.assign({}, {
      designWidth: 1080,
    }, options);
    if (!this.options.maxPageWidth) {
      this.options.maxPageWidth = this.options.designWidth;
    }
  }

  /**
   * 在html头部注入简版rem.js用以适配rem
   * @param data
   */
  generateRemJsCode(data) {
    data.head = data.head || [];
    let {designWidth, maxPageWidth} = this.options;
    let script = {
      tagName: 'script',
      closeTag: true,
      attributes: {
        type: 'text/javascript'
      },
      innerHTML:
        `
  !function (n) {
    var e = n.document,
      t = e.documentElement,
      i = ${designWidth},
      d = i / 100,
      o = 'orientationchange' in n ? 'orientationchange' : 'resize',
      a = function () {
        var n = t.clientWidth || 320;
        n > ${maxPageWidth} && (n = ${maxPageWidth});
        t.style.fontSize = n / d + 'px';
      };
    e.addEventListener && (n.addEventListener(o, a, !1), e.addEventListener('DOMContentLoaded', a, !1));
  }(window);
`
    };
    data.head.push(script);
  }

  apply(compiler) {
    // HtmlWebpackPlugin version 4.0.0-beta.5
    if (HtmlWebpackPlugin.getHooks) {
      compiler.hooks.compilation.tap('HtmlWebpackPxToRemPlugin', (compilation) => {
        HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync(
          'HtmlWebpackPxToRemPlugin', (data, callback) => {
            this.generateRemJsCode(data);
            callback(null, data);
          }
        );
      });
    } else {
      // HtmlWebpackPlugin version 3.2.0
      compiler.plugin('compilation', compilation => {
        compilation.plugin('html-webpack-plugin-alter-asset-tags', data => {
          this.generateRemJsCode(data);
        });
      });
    }
  }
}

module.exports = HtmlWebpackPxToRemPlugin;
